<template>
  <div class="contain-div">
    <el-image
      class="img-cut"
      :src="require('@/assets/images/imgChessBg.jpg')"
      fit="cover"
    />
    <el-card class="form" shadow="hover">
      <el-form
        :model="formData"
        :rules="rules"
        ref="modelForm"
        class="form-body-gap"
      >
        <FormItem
          :renderList="renderList"
          :formData="formData"
        />
        <FormBottom
          :formType="formName"
          @submitForm="submit"
          @resetForm="reset"
        />
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {userRegister, userLogin} from '@/api/index.js';
import FormBottom from '@/components/FormBottom.vue';
import FormItem from '@/components/FormItem.vue';
import formConf from '@/config/formConf.json';
const getRules = (name, conf) => (name === 'register' ? {
  rules: {
    pass: [
      {required: true, validator: conf.validatePass, trigger: 'change'}
    ],
    checkPass: [
      {required: true, validator: conf.validatePass2, trigger: 'change'}
    ],
    name: [
      {required: true, message: '请输入昵称', trigger: 'change'}
    ],
    email: [
      {required: true, validator: conf.validateEmail, trigger: 'change'}
    ]
  }
} : {
  rules: {
    user: [
      {required: true, message: '请输入用户名', trigger: 'change'}
    ],
    pass: [
      {required: true, message: '请输入密码', trigger: 'change'}
    ]
  }
});
export default {
  name: 'User',
  components: {
    FormBottom,
    FormItem
  },
  watch: {
    $route: {
      handler(val) {
        this.formName = val.meta.form;
      }
    }
  },
  computed: {
    renderList() {
      return formConf[this.formName];
    },
    rules() {
      return getRules(this.formName, this.validMap);
    }
  },
  data() {
    return {
      formName: 'login',
      formData: {
        pass: '',
        checkPass: '',
        name: '',
        email: '',
        user: ''
      },
      validMap: {
        validatePass: (_rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'));
          }
          else {
            if (this.formData.checkPass !== '') {
              this.$refs.modelForm.validateField('checkPass');
            }
            callback();
          }
        },
        validatePass2: (_rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'));
          }
          else if (value !== this.formData.pass) {
            callback(new Error('两次输入密码不一致!'));
          }
          else {
            callback();
          }
        },
        validateEmail: (_rule, value, callback) => {
          const verify = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
          if (!verify.test(value)) {
            callback(new Error('请输入正确的邮箱'));
          }
          else {
            callback();
          }
        }
      }
    };
  },
  methods: {
    submit() {
      this.$refs.modelForm.validate(valid => {
        if (valid) {
          // 这么写可读性好像变差了-大致意思是根据字符串名字选择执行的函数
          ({login: this.loginFunc, register: this.registerFunc})[this.formName]();
        }
        else {
          this.$message({
            type: 'warning',
            message: '输入信息无效'
          });
        }
      });
    },
    registerFunc() {
      userRegister(this.formData).then(res => {
        if (res.data.succeed) {
          this.$message({
            type: 'success',
            message: '恭喜你，注册成功！'
          });
          this.$router.push({name: 'login'});
        }
        else {
          this.$message('对不起，注册失败了');
        }
      });
    },
    loginFunc() {
      userLogin(this.formData).then(res => {
        if (res.data.succeed) {
          this.$message({
            type: 'success',
            message: '登陆成功'
          });
          const {id, level, win, session, escape, url} = res.data;
          this.$cookies.set('user', {
            id,
            level,
            session,
            rate: win,
            headUrl: url,
            name: this.formData.user,
            escape: `${Number(escape * 100).toFixed(1)}%`
          }, '1d');
          this.$router.push({name: 'hall'});
        }
        else {
          this.$message.error('用户名或密码错误');
        }
      });
    },
    reset() {
      this.$refs.modelForm.resetFields();
    }
  },
  created() {
    // cookie验证
    if (this.$cookies.isKey('user')) {
      this.$confirm('检测到您已登录, 是否注销账户?', '提示', {
        confirmButtonText: '注销账户',
        cancelButtonText: '去大厅看看',
        type: 'warning'
      }).then(() => {
        this.$cookies.remove('user');
        this.$message({
          type: 'success',
          message: '注销成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        });
        this.$router.push({name: 'hall'});
      });
    }
  }
};
</script>

<style scoped>
.contain-div {
  position: relative;
  height: 100%;
  overflow-y: hidden;
}
.form-body-gap {
  padding-top: 20px;
  box-sizing: border-box;
}
.img-cut {
  height: 100%;
  width: 100%;
}
</style>
